using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using CSW.Framework.Common;

namespace CSW.Framework.UI.DevEx.Binding
{
    /// <summary>
    /// <see cref="BaseEdit"/> event handlers.
    /// </summary>
    public static class BaseEditEventHandlers
    {
        /// <summary>
        /// Handles the delete button's click event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DevExpress.XtraEditors.Controls.ButtonPressedEventArgs"/> instance containing the event data.</param>
        public static void DeleteButtonClick(object sender, ButtonPressedEventArgs e)
        {
            Guard.ArgumentNotNull(sender, "sender");
            Guard.ArgumentNotNull(e, "e");

            if (e.Button.Kind == ButtonPredefines.Delete)
            {
                ClearValue((BaseEdit)sender);
            }
        }

        /// <summary>
        /// Handles the delete key's down event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
        public static void DeleteKeyDown(object sender, KeyEventArgs e)
        {
            Guard.ArgumentNotNull(sender, "sender");
            Guard.ArgumentNotNull(e, "e");

            if (e.KeyCode == Keys.Delete)
            {
                ClearValue((BaseEdit)sender);
                e.SuppressKeyPress = true;
            }
        }

        private static void ClearValue(BaseEdit baseEdit)
        {
            Guard.ArgumentNotNull(baseEdit, "baseEdit");

            if (!baseEdit.Properties.ReadOnly)
            {
                baseEdit.EditValue = null;
                baseEdit.Tag = null;
                baseEdit.DoValidate();
            }
        }
    }
}